package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 用户下单
     * @param orders
     */
    @Transactional
    public void submit(Orders orders) {
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();

        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);

        if(shoppingCarts == null || shoppingCarts.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }

        //查询用户数据
        User user = userService.getById(userId);

        //查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if(addressBook == null){
            throw new CustomException("用户地址信息有误，不能下单");
        }

        long orderId = IdWorker.getId();//订单号

        AtomicInteger amount = new AtomicInteger(0);

        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
//        orders.setUserName(user.getName());
        orders.setUserName(String.valueOf(userId));
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.remove(wrapper);
    }

    /**
     * 移动端查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public R<Page> userPage(int page, int pageSize) {
        Page<OrdersDto> pageInfo = new Page<>(page,pageSize);
        List<OrdersDto> ordersDtos = orderMapper.userPage(pageInfo);
        pageInfo.setRecords(ordersDtos);
        log.info("page:{}",pageInfo);
        return R.success(pageInfo);
    }

    /**
     * pc端分页查询
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public R<Page> page(Integer page, Integer pageSize, String number, Date beginTime, Date endTime) {
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(number!=null, Orders::getNumber, number);
        lqw.ge(beginTime!=null,Orders::getOrderTime, beginTime);
        lqw.le(endTime!=null,Orders::getOrderTime, endTime);
        this.page(pageInfo,lqw);
        log.info("page:{}",pageInfo);
        return R.success(pageInfo);
    }

    /**
     * 修改派送转态
     * @param orders
     * @return
     */
    @Override
    public R<String> update(Orders orders) {
        this.updateById(orders);
        return R.success("派送完成");
    }

    /**
     * 再來一单
     * @param orders
     * @return
     */
    @Override
    public R<String> again(Orders orders) {
        log.info(orders.toString());
        //设置用户id 指定当前是哪个用户的购物车数据
        Long currentId = BaseContext.getCurrentId();
        //得到订单id
        Long ordersId = orders.getId();
        LambdaQueryWrapper<Orders> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId,ordersId);
        //根据订单id得到订单元素
        Orders one = this.getOne(queryWrapper);
        //得到订单表中的number 也就是订单明细表中的order_id
        String number = one.getNumber();

        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderDetail::getOrderId,number);
        //根据订单明细表的order_id得到订单明细集合
        List<OrderDetail> orderDetails = orderDetailService.list(lambdaQueryWrapper);
        //新建购物车集合
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        //通过用户id把原来的购物车给清空
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
        //遍历订单明细集合,将集合中的元素加入购物车集合
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            //得到菜品id或套餐id
            Long dishId = orderDetail.getDishId();
            Long setmealId = orderDetail.getSetmealId();
            //添加购物车部分属性
            shoppingCart.setUserId(currentId);
            shoppingCart.setDishFlavor(orderDetail.getDishFlavor());
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCart.setAmount(orderDetail.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            if(dishId!=null){
                //订单明细元素中是菜品
                LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
                dishLambdaQueryWrapper.eq(Dish::getId,dishId);
                //根据订单明细集合中的单个元素获得单个菜品元素
                Dish dishone = dishService.getOne(dishLambdaQueryWrapper);
                //根据菜品信息添加购物车信息
                shoppingCart.setDishId(dishId);
                shoppingCart.setName(dishone.getName());
                shoppingCart.setImage(dishone.getImage());
                //调用保存购物车方法
                shoppingCarts.add(shoppingCart);
            }
            else if(setmealId!=null){
                //订单明细元素中是套餐
                LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
                setmealLambdaQueryWrapper.eq(Setmeal::getId,setmealId);
                //根据订单明细集合中的单个元素获得单个套餐元素
                Setmeal setmealone = setmealService.getOne(setmealLambdaQueryWrapper);
                //根据套餐信息添加购物车信息
                shoppingCart.setSetmealId(setmealId);
                shoppingCart.setName(setmealone.getName());
                shoppingCart.setImage(setmealone.getImage());
                //调用保存购物车方法
                shoppingCarts.add(shoppingCart);
            }
        }
        shoppingCartService.saveBatch(shoppingCarts);
        return R.success("操作成功");
    }
}